`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company: 
// Engineer: 
// 
// Create Date: 2023/11/04 11:29:09
// Design Name: 
// Module Name: DAC_Delay_PPS
// Project Name: 
// Target Devices: 
// Tool Versions: 
// Description: 
// 
// Dependencies: 
// 
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
// 
//////////////////////////////////////////////////////////////////////////////////


module DAC_Delay_PPS(
    input ADC_CLK,
    input BRAM_PORTA_clk,
    input rst_n,
    input [31:0] PPS_ref_cnt,
    input DAC_MARK,
    input [31:0] reset_val,
    output reg [31:0] Delay_cnt
    );

localparam Start_lock = 10000000;

reg DAC_MARK_D1, DAC_MARK_D2;
reg [31:0] Delay_cnt_lock;
always @(posedge ADC_CLK or negedge rst_n) begin
    if (!rst_n) begin
		// reset
		DAC_MARK_D1 <= 1'b0;
        DAC_MARK_D2 <= 1'b0;
	end
    else begin
        DAC_MARK_D1 <= DAC_MARK;
        DAC_MARK_D2 <= DAC_MARK_D1;
    end
end

wire [31:0] reset_val_out;
reg [31:0] reset_val_out_reg;
Async_to_sync reset_fifo (
  .rst(!rst_n),                  // input wire rst
  .wr_clk(BRAM_PORTA_clk),            // input wire wr_clk
  .rd_clk(ADC_CLK),            // input wire rd_clk
  .din(reset_val),                  // input wire [31 : 0] din
  .wr_en(1'b1),              // input wire wr_en
  .rd_en(1'b1),              // input wire rd_en
  .dout(reset_val_out),                // output wire [31 : 0] dout
  .full(),                // output wire full
  .empty(),              // output wire empty
  .wr_rst_busy(),  // output wire wr_rst_busy
  .rd_rst_busy()  // output wire rd_rst_busy
);

reg reset_flag;

always @(posedge ADC_CLK or negedge rst_n) begin
    if (!rst_n) begin
		// reset
		reset_val_out_reg   <= 32'd0;
	end
    else begin
        reset_val_out_reg <= reset_val_out;
    end
end
always @(posedge ADC_CLK or negedge rst_n) begin
    if (!rst_n) begin
		// reset
		reset_flag    <= 1'b0;
	end
    else if(reset_val_out_reg!=reset_val_out) begin
        reset_flag  <= 1'b1;
    end
    else begin
        reset_flag  <= 1'b0;
    end
end


always @(posedge ADC_CLK or negedge rst_n) begin
    if (!rst_n) begin
		// reset
		Delay_cnt_lock   <= 32'hffffffff;
	end
    else if(DAC_MARK_D1==1'b1 && DAC_MARK_D2==1'b0) begin
        Delay_cnt_lock   <= PPS_ref_cnt;
    end
    else if(reset_flag==1'b1) begin
        Delay_cnt_lock   <= 32'hffffffff;
    end
    else begin
        Delay_cnt_lock   <= Delay_cnt_lock;
    end

end



always @(posedge ADC_CLK or negedge rst_n) begin
    if (!rst_n) begin
		// reset
		Delay_cnt   <= 32'hffffffff;
	end
    else if(PPS_ref_cnt>=Start_lock) begin
        Delay_cnt <= Delay_cnt_lock;
    end
    else begin
        Delay_cnt   <= Delay_cnt;
    end

end



endmodule
